package com.cens.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.cens.common.constant.AuthConstant;
import com.cens.common.exception.BaseCodeEnum;
import com.cens.common.utils.R;
import com.cens.common.vo.MemberEntityVo;
import com.cens.mall.auth.feign.MemberFeignService;
import com.cens.mall.auth.feign.ThirdPartyFeignService;
import com.cens.mall.auth.vo.UserLoginVo;
import com.cens.mall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 1、接口防刷

        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode) &&
                System.currentTimeMillis() - Long.parseLong(redisCode.split("_")[1]) < 60 * 1000) {
            //60秒内同一手机号不能再次发送
            return R.error(BaseCodeEnum.VALID_SMS_CODE.getCode(), BaseCodeEnum.VALID_SMS_CODE.getMsg());
        } else {
            String code = UUID.randomUUID().toString().substring(0, 5);
            //2、验证码再次校验 redis存储
            stringRedisTemplate.opsForValue()
                    .set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 1, TimeUnit.MINUTES);

            thirdPartyFeignService.sendCode(phone, code);
        }

        return R.ok();
    }

    /**
     * //TODO 重定向携带数据，将数据放在session中，只要调到下一个页面取出数据以后，session里的数据就会删掉
     * //TODO 分布式下的session问题
     *
     * @param userRegistVo
     * @param bindingResult
     * @param redirectAttributes 模拟重定向携带数据
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userRegistVo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.groupingBy(FieldError::getField))
                    .entrySet()
                    .stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","))));
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.censmall.com/reg.html";
        }
        //校验验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
        if (StringUtils.isNotEmpty(redisCode) && Objects.equals(redisCode.split("_")[0], userRegistVo.getCode())) {
            //删除验证码
            stringRedisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
            //注册
            R r = memberFeignService.regist(userRegistVo);
            if (r.getCode() == 0) {
                //注册成功回到登录页
                return "redirect:http://auth.censmall.com/login.html";
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", r.getData("msg", new TypeReference<String>() {
                }));
                redirectAttributes.addFlashAttribute("errors", errors);
                //注册失败
                return "redirect:http://auth.censmall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.censmall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(@Valid UserLoginVo userLoginVo, BindingResult bindingResult, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.login(userLoginVo);
        if (r.getCode() != 0) {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            //登录失败
            return "redirect:http://auth.censmall.com/login.html";
        }
        MemberEntityVo data = r.getData("data", new TypeReference<MemberEntityVo>() {
        });
        session.setAttribute(AuthConstant.LOGIN_USER,data);
        //登录成功返回首页
        return "redirect:http://censmall.com";
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession httpSession){
        Object attribute = httpSession.getAttribute(AuthConstant.LOGIN_USER);
        if(attribute == null){

            return "login";
        }else{
            //登录成功返回首页
            return "redirect:http://censmall.com";
        }
    }
}
